package com.wanyl.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    public static Map<String,Object>getConf(String[] args){
        Map<String ,Object> config=new HashMap<>();
        config.put("port","8001");
        String keys="";
        for (int i=0;i<args.length;i++){
            if(args[i].startsWith("--")){
                String p=args[i].substring(2).trim();
                if(p.length()==0)continue;
                keys=p;
                config.put(keys,"");
                continue;
            }else {
                //config[keys]=args.trim();
                if(keys.equals(""))continue;
                config.put(keys,args[i]);
                keys="";
            }
        }
        int port=Integer.parseInt((String)config.get("port"));
        if(port<1000){
            System.err.println("port is null,need append command --port [>1000]");
            System.exit(1);
        }
        if(Tool.isPortUsing("127.0.0.1",port)){
            System.err.println("port["+port+"] is used,please replace it. ");
            System.exit(1);
        }
        return config;
    }


    public static void main(String[] args) throws IOException {
        Map<String, Object> config = getConf(args);


        HttpServer server = HttpServer.create(new InetSocketAddress(Integer.parseInt((String)config.get("port"))), 0);

        server.createContext("/",new LocalResource());
        server.createContext("/getApi", new GetHandler());
        server.createContext("/postApi", new GetHandler());
        server.createContext("/static", new staticHandler());
        server.createContext("/db", new DbHandler());
        server.start();
        System.out.println("[Listen] 0.0.0.0:8001");
        System.out.println("[API] /getApi");
        System.out.println("[API] /postApi");
        System.out.println("[API] /db");
        System.out.println("============================");
        while(true){
            Scanner sc=new Scanner(System.in);
            String li=sc.nextLine();
            if(li==null)continue;
            li=li.trim();
            if(li.equals("exit")){
                server.stop(1000);
                break;
            }
        }
    }
    static  class GetHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {

//            System.out.println(exchange.getRequestMethod().toLowerCase());
            if(exchange.getRequestMethod().toLowerCase().equals("options")){
                exchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");
                exchange.getResponseHeaders().add("Access-Control-Allow-Methods","POST");
                exchange.getResponseHeaders().add("Access-Control-Max-Age","3600");
                exchange.getResponseHeaders().add("Access-Control-Allow-Headers","x-requested-with");
                exchange.getResponseHeaders().add("Access-Control-Allow-Headers","content-type");
                exchange.sendResponseHeaders(204,0);
                exchange.close();
                return;
            }else if(!exchange.getRequestMethod().toLowerCase().equals("post")){
                exchange.sendResponseHeaders(500,0);
                exchange.close();
                return;
            }

            String data=null;
            String url = exchange.getRequestURI().toString();
            System.out.println("[ URL ]"+url);
            try{
                if(url.contains("/getApi")){
                    data = Handller_call.doCall(exchange);
                }else if(url.contains("/postApi")){
                    data = Handller_call.doCall_Post(exchange);
                }
                }catch (Exception e){}

//            exchange.getResponseBody().
            if(data!=null){
                exchange.getResponseBody().write(data.getBytes("UTF-8"));
            }
            exchange.close();
        }
    }

    static class Handller_call{
        public static String doCall(HttpExchange exchange) throws IOException {
//            if(exchange.)
            InputStream ins = exchange.getRequestBody();
//            ins.available()
            byte[] s=new byte[4096];
            ins.read(s);
            DataGetModel dgm;
            System.out.println("用户进入，数据已到达");
            try{dgm = new DataGetModel(JSON.parseObject(new String(s)));}catch (Exception e){
                e.printStackTrace();
                return null;
            }



            String url = dgm.getString("url", "");
            String head = dgm.getString("head", "");
//            String  = dgm.getString("head", "");
            int timeout = dgm.getInt("timeout", 5000);
            boolean allow_reDirect=dgm.getBoolean("redirect",true);
            String callid=dgm.getString("callid", "-1");
//            System.out.println("解析数据中");
            System.out.println("解析到url:"+url);
            if(url.equals("")){return null;}
//            System.out.println("即将发送");
//            String response = "hello world";
            Map p=new HashMap();
            try {
                p=HttpClient.doGetTestWayTwo(url,head,allow_reDirect,timeout,callid);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            System.out.println("取回数据");


            exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
            exchange.sendResponseHeaders(200, 0);


            exchange.setAttribute("test","123");

            OutputStream os = exchange.getResponseBody();

//            System.out.println("写入中");

            p.put("tip","执行成功");
            return JSON.toJSONString(p);
//            os.close();
        }
        public static String doCall_Post(HttpExchange exchange) throws IOException {
            InputStream ins = exchange.getRequestBody();
            DataGetModel dgm;
            System.out.println("解析数据");
            byte[] s=new byte[ins.available()];

            ins.read(s);

            System.out.println("用户进入，数据已到达");
            System.out.println(new String (s));
            try{dgm = new DataGetModel(JSON.parseObject(new String(s)));}catch (Exception e){
                e.printStackTrace();
                return null;
            }


            String url = dgm.getString("url", "");
            String head = dgm.getString("head", "");
            String data = dgm.getString("data", "");
//            String  = dgm.getString("head", "");
            int timeout = dgm.getInt("timeout", 5000);
            boolean allow_reDirect=dgm.getBoolean("redirect",true);
            String callid=dgm.getString("callid", "-1");
            System.out.println("解析数据中");
            if(url.equals("")){return null;}
            System.out.println("即将发送");
//            String response = "hello world";
            Map p=new HashMap();
            try {
                p=HttpClient.doPostTestTwo(url,head,allow_reDirect,timeout,callid,data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("取回数据");
            exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
            exchange.sendResponseHeaders(200, 0);

            OutputStream os = exchange.getResponseBody();

            System.out.println("写入中");
            return JSON.toJSONString(p);
//            os.close();
        }
    }

    public static class DataGetModel{
        JSONObject s;
        public DataGetModel(JSONObject s){
            this.s=s;
        }
        public String getString(String key,String defaultV){
            try{
                String v = s.getString(key);
                if(v==null)return defaultV;
                return v;
            }catch (Exception e){
                return defaultV;
            }
        }
        public int getInt(String key,int defaultV){
            try{
                if(s.get(key)==null)return defaultV;
                int v = s.getInteger(key);
                return v;
            }catch (Exception e){
                return defaultV;
            }
        }
        public boolean getBoolean(String key,boolean defaultV){
            try{
                if(s.get(key)==null)return defaultV;
                boolean v = s.getBoolean(key);
                return v;
            }catch (Exception e){
                return defaultV;
            }
        }
    }
}
